﻿using System;
using System.Timers;

namespace DotNetClient
{
    public class HeartbeatService
    {
        private int _interval;
        private int _timeout;
        private Timer _timer;
        private DateTime _lastTime;
        private Protocol _protocol;

        public HeartbeatService(float heartbeatTime, Protocol protocol)
        {
            _interval = (int)(heartbeatTime * 1000);
            _protocol = protocol;
        }

        public void start()
        {
            if (_interval < 1000) return;

            // start hearbeat
            _timer = new Timer();
            _timer.Interval = _interval;
            _timer.Elapsed += new ElapsedEventHandler(sendHeartBeat);
            _timer.Enabled = true;

            // Set timeout
            _timeout = 0;
            _lastTime = DateTime.Now;
        }

        internal void resetTimeout()
        {
            _timeout = 0;
            _lastTime = DateTime.Now;
        }

        public void sendHeartBeat(object source, ElapsedEventArgs e)
        {
            TimeSpan span = DateTime.Now - _lastTime;
            _timeout = (int)span.TotalMilliseconds;

            // check timeout
            if (_timeout > _interval * 2)
            {
                UnityEngine.Debug.LogError("HeartBeat timeout!");
                _protocol.Client.Disconnect();
                //stop();
                return;
            }

            // Send heart beat
            _protocol.send(PackageType.PKG_HEARTBEAT);
        }

        public void stop()
        {
            if (_timer != null)
            {
                _timer.Enabled = false;
                _timer.Dispose();
            }
        }
    }
}
